package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class CompleteSupplyTaskHandler implements MsgHandler {
    @Autowired
    private VendingMachineService vendingMachineService;
    @Autowired
    private ChannelService channelService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //json转成对象
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        //开始更新售货机中的库存数量
        //1.更新售货机上一次补货时间
        LambdaUpdateWrapper<VendingMachineEntity> VendingMachineEntityUpdateWrapper = new LambdaUpdateWrapper<>();
        VendingMachineEntityUpdateWrapper.eq(VendingMachineEntity::getInnerCode,supplyContract.getInnerCode())
                .set(VendingMachineEntity::getLastSupplyTime, LocalDateTime.now());
        vendingMachineService.update(VendingMachineEntityUpdateWrapper);
        //2.开始更新货道信息
        LambdaUpdateWrapper<ChannelEntity> channelEntityUpdateWrapper = new LambdaUpdateWrapper<>();

        //根据售货机编号查询售货机的货道
        List<ChannelEntity> channelByInnerCode = channelService.getChannelesByInnerCode(supplyContract.getInnerCode());
        //工单的补货数据
        List<SupplyChannel> supplyData = supplyContract.getSupplyData();

        //把接收到的消息（工单详情）拼装成map
        Map<String, SupplyChannel> map = new HashMap();
        for (SupplyChannel supplyDatum : supplyData) {
            map.put(supplyDatum.getChannelId(),supplyDatum);
        }
        for (ChannelEntity channelEntity : channelByInnerCode) {
            if(channelEntity.getSkuId() != 0){
                //根据货道编号取出工单详情中的某个具体的货道信息
                SupplyChannel supplyChannel = map.get(channelEntity.getChannelCode());
                //修改当前库存 还有时间
                channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity() + supplyChannel.getCapacity());
                channelEntity.setLastSupplyTime(LocalDateTime.now());
                //更新售货机的每个货道的库存和时间
                channelService.updateById(channelEntity);
            }
        }
    }
}
